package com.yonyougov.devops.cruxcisupport.k8s;

import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import com.yonyougov.devops.cruxcisupport.kubeconfig.KubeConfigEntity;
import com.yonyougov.devops.cruxcisupport.kubeconfig.KubeConfigService;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

@Repository
@Slf4j
public class K8sRepositoryImpl implements K8sRepository {
    private final KubeConfigService kubeConfigService;

    public K8sRepositoryImpl(KubeConfigService kubeConfigService) {
        this.kubeConfigService = kubeConfigService;
    }

    @Override
    public KubernetesClient createDefaultClient(String envName) throws K8sConfIgNotFindException {
        KubeConfigEntity kubeConfigEntity = kubeConfigService.findByEnvName(envName);
        if(null == kubeConfigEntity || StringUtils.isBlank(kubeConfigEntity.getContent())){
            throw new K8sConfIgNotFindException("在数据库表t_kube_config中找不到环境: "+envName+"的配置项，请检查");
        }
        log.info("kubConfig loading: {}",kubeConfigEntity.getContent());
        Config config = Config.fromKubeconfig(envName, kubeConfigEntity.getContent(), null);
        return new DefaultKubernetesClient(config);
    }
}
